package com.yqg.manage.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.yqg.manage.common.Result;
import com.yqg.manage.common.interceptor.SysLog;
import com.yqg.manage.entity.Archive;
import com.yqg.manage.entity.Params;
import com.yqg.manage.service.IArchiveService;
import com.yqg.manage.service.ICaseArchiveStageService;
import com.yqg.manage.service.IParamsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ParamsController 前端控制器
 *
 * @author suzhuang
 * @since 2023-07-05
 */
@RestController
@Api(tags = "卷宗文书管理")
@RequestMapping("/params")
public class ParamsController {

    @Resource
    private IParamsService paramsService;

    @Resource
    private IArchiveService archiveService;

    @Resource
    private ICaseArchiveStageService caseArchiveStageService;

    @Value("${upload.path}")
    private String path;

    @ApiOperation("判断该文书能否打印")
    @GetMapping("/isPrint")
    public Result isPrint(String caseNo, String templateNo) {
        List<Long> list = caseArchiveStageService.passStage(caseNo);
        QueryWrapper<Archive> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("template_no", templateNo);
        Archive theArchive = archiveService.getOne(queryWrapper);
        return Result.success(list.contains(theArchive.getPstageId()));
    }

    /**
     * 新增或者更新
     */
    @ApiOperation("新增或者更新")
    @PostMapping("/edit")
    @SysLog("新增或者更新案件文书")
    public Result save(@RequestBody Params params) {

        Params one = paramsService.getById(params.getId());
        if (one == null) {//新增
            params.setUpload_time(new Date());
            params.setStatus("0");
            paramsService.saveOrUpdate(params);

            // 获取PDF路径
            LambdaQueryWrapper<Archive> archiveLambdaQueryWrapper = new LambdaQueryWrapper<>();
            archiveLambdaQueryWrapper.eq(Archive::getTemplateNo, params.getTemplateNo());
            Archive archive = archiveService.getOne(archiveLambdaQueryWrapper);
            String pdfName = "api/file/download/" + path + archive.getDocumentName() + params.getId() + ".pdf";

            params.setPdf(pdfName);
            boolean b = paramsService.saveOrUpdate(params);
            if (b) {
                return Result.success(params);
            }
        } else {
            one.setParamContent(params.getParamContent());

            // 获取PDF路径
            LambdaQueryWrapper<Archive> archiveLambdaQueryWrapper = new LambdaQueryWrapper<>();
            archiveLambdaQueryWrapper.eq(Archive::getTemplateNo, one.getTemplateNo());
            Archive archive = archiveService.getOne(archiveLambdaQueryWrapper);
            String pdfName = "api/file/download/" + path + archive.getDocumentName() + one.getId() + ".pdf";

            one.setPdf(pdfName);
            boolean b = paramsService.saveOrUpdate(one);
            if (b) {
                return Result.success(one);
            }
        }
        return Result.error();
    }

    /**
     * 删除
     */
    @GetMapping("delete/{id}")
    @SysLog("删除案件文书")
    public Result delete(@PathVariable Integer id) {
        Params params = paramsService.getById(id);
        return Result.success(paramsService.removeById(params));
    }

    /**
     * 通过id设置status
     */
    @ApiOperation("通过id设置status")
    @GetMapping("/changeStatus")
    public Result changeSt(@RequestParam Integer id, @RequestParam String status) {
        Params params = paramsService.getById(id);
        params.setStatus(status);
        return Result.success(paramsService.saveOrUpdate(params));
    }

    /**
     * 查询所有
     */
    @GetMapping("/all")
    public Result findAll() {
        List<Params> list = paramsService.list();
        return Result.success(list);
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(paramsService.getById(id));
    }

    /**
     * 通过案件编号和文书Id查询记录
     */
    @GetMapping("/getDoc")
    public Result getDoc(String caseId, String templateNo) {
        LambdaQueryWrapper<Params> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Params::getCaseId, caseId);
        queryWrapper.eq(Params::getTemplateNo, templateNo);
        List<Params> paramsList = paramsService.list(queryWrapper);
        return Result.success(paramsList);
    }

    /**
     * 分页查询
     * 按时间倒序排序
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Long caseId,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize
//            , @RequestParam(required = false) String name) {
    ) {
        IPage<Params> page = paramsService.selectJoinListPage(
                new Page<>(pageNum, pageSize),
                Params.class,
                new MPJLambdaWrapper<Params>()
                        .select(Params::getCaseId, Params::getId, Params::getTemplateNo, Params::getStatus, Params::getUpload_time, Params::getPdf)
                        .select(Archive::getDocumentName, Archive::getPstageId)
                        .leftJoin(Archive.class, Archive::getTemplateNo, Params::getTemplateNo)
                        .eq(Params::getCaseId, caseId)
                        .orderByDesc(Params::getUpload_time)
//                        .like(Archive::getDocumentName,name)
        );
        return Result.success(page);
    }

    /**
     * 文书数据
     *
     * @param params
     * @return
     */
    @PostMapping("/paramContent")
    public Result fetchData(@RequestBody Params params) {
        // 创建一个条件构造器
        QueryWrapper<Params> queryWrapper = new QueryWrapper<>();
        // 根据前端传过来的 id,templateNo 和 caseNo 查询
        queryWrapper.eq("id", params.getId());
        queryWrapper.eq("template_no", params.getTemplateNo());
        queryWrapper.eq("case_id", params.getCaseId());
        // 调用 mybatisplus 的 service 层方法，获取查询结果
        Params result = paramsService.getOne(queryWrapper);
        // 判断查询结果是否为空，如果为空，返回错误信息
        if (result == null) {
            return Result.error("没有找到对应的 paramContent");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("paramContent", result.getParamContent());
        map.put("status", result.getStatus());
        // 如果不为空，返回成功信息和 paramContent
        return Result.success(map);
    }

    /**
     * 根据案件编号获取对应文书的PDF路径，用于结案导出PDF
     *
     * @param caseId 案件Id
     * @return （PDF路径和文书名称）的List集合
     */
    @GetMapping("/getPdfList")
    public Result getPdfList(@RequestParam String caseId) {
        return Result.success(paramsService.getPdfList(caseId));
    }


}

